import subprocess,re

back = 4
home = 3

def cmdexe(cmd,type=1):
    '''执行cmd'''
    if type == 2:
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE,shell=True)
    else:
        p = subprocess.Popen(cmd, shell=True)
    p.communicate()

def get_cmdexe_result(cmd):
    '''执行cmd并获取返回'''
    return str(subprocess.Popen(cmd, stdout=subprocess.PIPE,shell=True).stdout.read())

def screenshot(device,path):
    cmd1 = 'adb -s {0} shell /system/bin/screencap -p /sdcard/screenshot.png'.format(device)
    cmd2 = 'adb -s {0} pull /sdcard/screenshot.png {1}.png'.format(device, path)
    cmdexe(cmd1,2)
    cmdexe(cmd2,2)

def getWindowSize(device):
    cmd = 'adb -s {0} shell dumpsys window displays'.format(device)
    s = str(subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).stdout.read())
    group_obj = re.search(r'init=(\d*)x(\d*) ', s)

    return int(group_obj.group(2)), int(group_obj.group(1))

def startApp(device,package,startactivity):
    cmd = 'adb -s {0} shell am start -W {1}/{2}'.format(device,package,startactivity)
    cmdexe(cmd)

def closeApp(device,package):
    cmd = 'adb -s {0} shell am force-stop {1}'.format(device,package)
    cmdexe(cmd)

def sendkey(device,code):
    cmd = 'adb -s '+device+' shell input keyevent '+str(code)
    cmdexe(cmd)

def uninstall(device,package):
    cmd = 'adb -s {0} uninstall {1}'.format(device,package)
    cmdexe(cmd)

def tap_x_y(device,x,y):
    cmd = 'adb -s {0} shell input tap {1} {2}'.format(device, str(x), str(y))
    cmdexe(cmd)

def sendText(device,text):
    cmd = 'adb -s {0} shell input text {1}'.format(device, text)
    cmdexe(cmd)

def getCurActivity(device):
    cmd = 'adb -s {0} shell dumpsys activity activities'.format(device)
    return get_cmdexe_result(cmd)

def getSerialNo(device):
    cmd = 'adb -s 172.16.17.11:3701 shell getprop ro.serialno'
    return get_cmdexe_result(cmd).replace("b'",'').replace("\\r\\n'",'')

def getDeviceName():
    '''
    获取连接电脑上的设备名
    '''
    devices = []
    cmd = 'adb devices'
    s = get_cmdexe_result(cmd)
    for line in s.split('\\n'):
        if '\\tdevice' in line:
            devices.append(line.split('\\tdevice')[0])
    return devices

def checkBackActivity(device,package,startactivity):
    '''
    若当前app非指定app，则重新启动app
    '''
    s = getCurActivity(device)
    groupObj = re.search(r'mFocusedActivity: ActivityRecord{(.+)mFocusedStack',s)
    if not package in groupObj.group(1):
        startApp(device,package,startactivity)
